package spider.run;

import java.io.IOException;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentException;

import spider.data.Data;
import spider.process.Processer;
import spider.utils.xml.XmlManage;

/**
 * @说明：
 * @author: gaoll
 * @CreateTime:2014-11-14
 * @ModifyTime:2014-11-14
 */
public class RunSpider extends HttpServlet{
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int state = Integer.parseInt(req.getParameter("state").toString());
		long timeInteval = Long.parseLong(req.getParameter("timeInteval") == null ? "0":req.getParameter("timeInteval").toString());
		Data.timeInteval = timeInteval;
		boolean fixTime = req.getParameter("fixTime") == null? false:true;
		Data.fixTime = fixTime;
		XmlManage xml = new XmlManage();
		try {
			xml.xmlManage(req);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(state == 1){ //启动
			Data.launch = true;
			Data.startTime = new Date();
			Data.timer = new Timer();
			if(fixTime){
				Data.timer.schedule(new Processer(), 0, timeInteval); 
			}else{
				Data.timer.schedule(new Processer(), 0);
				Data.launch = false;
				Data.startTime = null;
			}
		}else{  //终止
			Data.launch = false;
			Data.startTime = null;
			Data.timer.cancel();
		}
		
		resp.sendRedirect("./state.jsp");
	}
	
	protected final Log log = LogFactory.getLog(getClass());
}
